<script>
import {addRole, deleteRole, queryAllRole, updateRole} from "@/api/systemAdministration/roleManagement/role";

let logo;
export default {
  data(){
    var checkRoleOrder = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 1) {
            callback(new Error('不能小于1'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      tableData:[],//table数据
      total:0,//总数量
      pageNum:1,//当前页
      pageSize:2,//每页显示数量
      pages:0, //总页数
      dialogFormVisible: false,//dialog显示隐藏
      //修改和新增Form数据
      Form:{
        roleID:0,
        roleName:"",
        roleOrder:0,
        description:""
      },
      //修改和新增约束
      FormRules: {
        roleName:[
          { required: true, message: '必填', trigger: 'blur' },
          { min: 2 ,max: 10, message: "长度2-10", trigger: "blur" }
        ],
        roleOrder:[
          { validator: checkRoleOrder, trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    this.getData();
  },
  methods:{
    //从后端获取数据
    getData(){
      queryAllRole(this.pageNum,this.pageSize)
        .then((data) => {
          if(data.code === 200){
            this.tableData = data.data.list;
            this.total = data.data.total;
            this.pages = data.data.pages;
          }
        })
        .catch((error) => {
          console.log(error);
        })
    },
    //修改
    handleEdit(row){
      logo = 'update'
      this.$refs.FormRef.clearValidate()
      this.Form = row;
      this.dialogFormVisible = true;
    },
    //分页切换显示数量时调用的方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    //分页切换页面时调用的方法
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getData();
    },
    handleAdd(){
      this.$refs.FormRef.clearValidate()
      logo = 'add';
      this.Form = {};
      this.dialogFormVisible = true;
    },
    //修改提交
    onSubmit(){
      this.$refs.FormRef.validate((valid) => {
        if(!valid) {
          this.$message.warning('兄嘚按规矩办事！！')
          return false;
        }else{
          if(logo === "update"){
            updateRole(this.Form)
              .then((data) => {
                if(data.code === 200){
                  this.$message({
                    message: '修改成功！！',
                    type: 'success'
                  });
                  this.dialogFormVisible = !this.dialogFormVisible;
                  this.getData();
                }else{
                  this.$message.error('修改失败！！');
                }
              })
              .catch((error) => {
                console.log(error);
              });
          }else if(logo === "add"){
            addRole(this.Form)
              .then((data) => {
                if(data.code === 200){
                  this.$message({
                    message: '新增成功！！',
                    type: 'success'
                  });
                  this.dialogFormVisible = !this.dialogFormVisible;
                  this.getData();
                }else{
                  this.$message.error('新增失败！！');
                }
              })
              .catch((error) => {
                console.log(error);
              });
          }
        }
      })
    },
    //删除
    handleDelete(row){
      this.$confirm('此操作将永久删除该角色，确认是否有用户使用该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.roleID)
          .then((data) =>{
            if(data.code === 200){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getData();
            }
          })
          .catch((error) =>{
            console.log(error);
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<template>
  <div style="margin-top:20px;">
    <el-button style="float: right;margin-right: 50px" @click="handleAdd">新增</el-button>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="roleOrder"
        align="center"
        label="排序">
      </el-table-column>
      <el-table-column
        align="center"
        label="名称">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>描述权限: {{ scope.row.description }}</p>
            <el-tag slot="reference" size="medium">{{ scope.row.roleName }}</el-tag>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handlePermissionSettings(scope.$index, scope.row)">权限设置</el-button>
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[2, 20, 50, 100]"
      :page-size="pageSize"
      style="text-align: center;"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
<!--    修改窗口-->
    <el-dialog
      title="修改角色"
      :visible.sync="dialogFormVisible"
      center
    >
      <el-form
        :model="Form"
        ref="FormRef"
        :rules="FormRules"
        status-icon
        style="margin-left: 100px">
        <el-form-item label="名称：" label-width="120px" prop="roleName">
          <el-input class="updateDialogFormStyle" v-model="Form.roleName"/>
        </el-form-item>
        <el-form-item label="排序：" label-width="120px" prop="roleOrder">
          <el-input class="updateDialogFormStyle" v-model.number="Form.roleOrder"/>
        </el-form-item>
        <el-form-item label="描述：" label-width="120px" prop="description">
          <el-input show-word-limit maxlength="50" class="updateDialogFormStyle" type="textarea" v-model="Form.description"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.updateDialogFormStyle{
  width: 250px;
}
.el-dialog{
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
